package com.cc.openeye.dynamic.kuikly.recommend

import com.cc.openeye.constance.RequestUrlConst
import com.cc.openeye.dynamic.DynamicModel
import com.cc.openeye.dynamic.recommend.entity.LoadMoreStatus
import com.cc.openeye.dynamic.recommend.entity.dynamicResponse.DynamicResponse
import com.cc.openeye.dynamic.recommend.entity.dynamicResponse.Item
import com.cc.openeye.dynamic.recommend.entity.dynamicResponse.LoadingInfo
import com.cc.openeye.dynamic.recommend.items.RecommendDynamicItemHelper
import com.cc.openeye.dynamic.recommend.items.RecommendDynamicItemHelper.ITEM_TYPE_DYNAMIC
import com.tencent.kuikly.core.base.PagerScope
import com.tencent.kuikly.core.coroutines.delay
import com.tencent.kuikly.core.coroutines.launch
import com.tencent.kuikly.core.manager.PagerManager
import com.tencent.kuikly.core.reactive.handler.observable
import com.tencent.kuikly.core.reactive.handler.observableList

class KuiklyRecommendViewModel(pagerScope: PagerScope) {

    private val dynamicModel by lazy {
        DynamicModel.newInstance()
    }

    var dynamicResponse by pagerScope.observable<DynamicResponse?>(null)

    val datas by pagerScope.observableList<Item>()

    private var requestUrl by pagerScope.observable(RequestUrlConst.DYNAMIC_URL)

    var loadMoreStatus by pagerScope.observable(LoadMoreStatus.NONE)

    private var isLoading = false

    suspend fun requestDynamicData(sence: String) {
        if (loadMoreStatus == LoadMoreStatus.NoMore) return
        if (isLoading) return
        isLoading = true
        loadMoreStatus = LoadMoreStatus.NONE
        println("====>sence:${sence}, isLoading：${isLoading}, requestUrl:${requestUrl}")
        val response = dynamicModel.requestDynamicData(requestUrl)
        if (response.success) {
            dynamicResponse = response.data
            datas.addAll(response.data?.getDataList() ?: emptyList())
            requestUrl = response.data?.nextPageUrl ?: ""
            loadMoreStatus =
                if (requestUrl.isNotEmpty()) LoadMoreStatus.HaveMore else LoadMoreStatus.NoMore
        } else {
            loadMoreStatus = LoadMoreStatus.LoadErr
        }
        isLoading = false
    }

    companion object {
        fun newInstance(pagerScope: PagerScope) = KuiklyRecommendViewModel(pagerScope)
    }
}